<template>
  <div class="iframe-wrapper">
    <div v-loading="isLoading" class="loading-mask">
      <!-- 内容容器 -->
      <iframe
      ref="iframeRef"
      :src="realUrl"
      frameborder="0"
      class="iframe-container"
      @load="handleIframeLoad"
      @error="handleIframeError"
    />
    </div>
    <div class="loading-text">{{ loadingTip }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useLayoutStore } from '@/store';

const layoutStore = useLayoutStore();
const route = useRoute();
const iframeRef = ref<HTMLIFrameElement>();
const currentUrl = ref('');
let menuItem = layoutStore.currentMenu;
let targetUrl = '';

// 新增加载状态控制
const isLoading = ref(true);
const loadingTip = ref('正在加载...');
const errorCount = ref(0);  // 错误计数器

if (menuItem.targetUrl) {
  targetUrl = menuItem.targetUrl;
}

const realUrl = computed(() => {
   return targetUrl;
});

// 监视URL变化触发加载
watch([realUrl], ([newUrl]) => {
  if (newUrl) {
    errorCount.value = 0;
    isLoading.value = true;
  }
});

const handleIframeLoad = () => {
  try {
    // 原有样式同步逻辑...
  } catch (e) {
    console.warn('iframe跨域警告', e);
  } finally {
    isLoading.value = false;
  }
};

const handleIframeError = () => {
  errorCount.value++;
  
  // 失败重试逻辑（最多3次）
  if (errorCount.value <= 3) {
    loadingTip.value = `加载失败，尝试重新连接（${errorCount.value}/3）`;
    setTimeout(() => {
      iframeRef.value?.contentWindow?.location.reload();
    }, 2000 * errorCount.value);
  } else {
    isLoading.value = false;
    loadingTip.value = '资源加载失败，请联系管理员';
  }
};
</script>

<style scoped>
/* 容器样式新增 */
.iframe-wrapper {
  position: relative;
  height: 100%;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-icon {
  font-size: 40px;
  color: var(--el-color-primary);
  animation: rotate 2s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  font-size: 14px;
  color: #666;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.iframe-container {
  width: 100%;
  height: 100%;
  min-height: calc(100vh - 120px);
}
</style>
